<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/16
 * Time: 13:13
 */

namespace App\Game\Traits;


use Mockery\Exception;

trait LgTrait
{

    public function getParameter(array $data)
    {
        $data['requesttime'] = time();
        $data['platformno'] = $this->platformNo;
        ksort($data);
        $signArray = $data;
        $signArray['key'] = $this->key;
        $sign = md5(http_build_query($signArray));
        $data['sign'] = $sign;

        return $this->encrypt(http_build_query($data), $this->key);
    }


    public function lgRequest(array $data, $url)
    {
        $parameter = $this->getParameter($data);
        $params['parameter'] = $parameter;
        $params['platformno'] = $this->platformNo;
        $url = $this->gameUrl . $url;
        $response = $this->request('POST', $url, $params,['Content-type'=>'application/x-www-form-urlencoded']);

        return $response;
    }


    public function encrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = openssl_cipher_iv_length('AES-256-ECB');
        $iv = openssl_random_pseudo_bytes($ivsize);

        $ciphertext = openssl_encrypt($message, 'AES-256-ECB', $key, OPENSSL_RAW_DATA, $iv);

        return base64_encode($iv . $ciphertext);
    }


    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->usernamePre($data);
        $data = $this->winCalculateParse($apiData, $data);
        return $data;
    }

    /**
     * gameapi
     * 2018/9/24 17:36
     * Administrator
     * winCalculateParse
     * 解析状态字段
     * @param array $apiData
     * @param array $data
     * @return array
     */
    private function winCalculateParse(array $apiData, array $data)
    {
        if (array_key_exists('winextract', $apiData)) {
            if($apiData['winextract']>0&& $data['company_win_amount']<0){
                $data['company_win_amount']=(abs($data['company_win_amount'])-1)*(-1);
                $data['company_payout_amount']=$data['company_payout_amount']-$apiData['winextract'];
            }
        }
        return $data;
    }

    /**
     * gameapi
     * 2019/1/28 22:55
     * Administrator
     * usernamePre
     *
     * @param array $data
     * @return array
     */
    private function usernamePre(array $data)
    {
        if (array_key_exists('username', $data)) {
            $data['username'] = str_after($data['username'], $this->clearPre);
        }
        return $data;
    }
}